﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System.Collections.Generic;

namespace NP.BPMReportPlatform.DBHelper
{
    public class SqlSugarAppService : BPMReportPlatformAppService, ISqlSugarAppService
    {
        /// <summary>
        /// 连接字符串
        /// </summary>
        private readonly string _connBusiness, _connPlatform, _connProcess, _connEngine, _connTodoCentre,
            _connEngineEventBus, _connEngineEventBus2, _connNIPWolkFlow, _conn_NIP_Wechat, _conn_NIP_Wechat_History;
        private readonly string _connSUS;
        private readonly string _connNPPlatformManage;

        /// <summary>
        /// 扩展方法
        /// </summary>
        private readonly ISqlFuncExtension _sqlFuncExtension;

        private readonly ILogger<SqlSugarAppService> _logger;

        // 从库
        private readonly string _connReadOnlyBusiness, _connReadOnlyPlatform,
            _connReadOnlyProcess, _connReadOnlyEngine, _connReadOnlyTodoCentre;

        private static readonly string filterPattern = @"^\s*(insert|delete|update|drop|create|alter|truncate)\s";

        public SqlSugarAppService(IConfiguration configuration, ILogger<SqlSugarAppService> logger, ISqlFuncExtension sqlFuncExtension)
        {
            _logger = logger;
            _connBusiness = configuration["ConnectionStrings:BPM_Business"];
            _connProcess = configuration["ConnectionStrings:BPM_Process"];
            _connPlatform = configuration["ConnectionStrings:BPM_Platform"];
            _connEngine = configuration["ConnectionStrings:BPM_Engine"];
            _connTodoCentre = configuration["ConnectionStrings:BPM_TodoCentre"];
            _connEngineEventBus = configuration["ConnectionStrings:BPM_EngineEventBus"];
            _connEngineEventBus2 = configuration["ConnectionStrings:BPM_EngineEventBus2"];
            _connNIPWolkFlow = configuration["ConnectionStrings:BPM_NIPWorkFlow"];
            _conn_NIP_Wechat = configuration["ConnectionStrings:BPM_NIP_Wechat"];
            _conn_NIP_Wechat_History = configuration["ConnectionStrings:BPM_NIP_Wechat_History"];
            _connSUS = configuration["ConnectionStrings:SUS"];
            _connNPPlatformManage = configuration["ConnectionStrings:IDS_NPPlatformManage"];
            _sqlFuncExtension = sqlFuncExtension;
            _connReadOnlyBusiness = configuration["ConnectionReadStrings:BPM_Business"];
            _connReadOnlyProcess = configuration["ConnectionReadStrings:BPM_Process"];
            _connReadOnlyPlatform = configuration["ConnectionReadStrings:BPM_Platform"];
            _connReadOnlyEngine = configuration["ConnectionReadStrings:BPM_Engine"];
            _connReadOnlyTodoCentre = configuration["ConnectionReadStrings:BPM_TodoCentre"];
        }

        //创建获取Business实例 ，isReadOnly=true 连接从库
        public SqlSugarClient GetBusinessInstance()
        {
            return GetInstance(_connBusiness, _connReadOnlyBusiness);
        }

        //创建获取Process实例 
        public SqlSugarClient GetProcessInstance()
        {
            return GetInstance(_connProcess, _connReadOnlyProcess);
        }

        //创建获取Platform实例 
        public SqlSugarClient GetPlatformInstance()
        {
            return GetInstance(_connPlatform, _connReadOnlyPlatform);
        }

        //创建获取Engine实例 
        public SqlSugarClient GetEngineInstance()
        {
            return GetInstance(_connEngine, _connReadOnlyEngine);
        }

        //创建获取ToDoCenter实例 
        public SqlSugarClient GetToDoCenterInstance()
        {
            return GetInstance(_connTodoCentre, _connReadOnlyTodoCentre);
        }

        //创建获取EngineEventBus实例 
        public SqlSugarClient GetEngineEventBusInstance()
        {
            return GetInstance(_connEngineEventBus);
        }

        //创建获取EngineEventBus2实例 
        public SqlSugarClient GetEngineEventBus2Instance()
        {
            return GetInstance(_connEngineEventBus2);
        }

        //创建获取老BPM NIP_WorkFlow实例 SqlServer数据库
        public SqlSugarClient GetNIPWolkFlowInstance()
        {
            return GetSqlServerInstance(_connNIPWolkFlow);
        }

        //创建获取老BPM NIP_Wechat SqlServer数据库
        public SqlSugarClient GetNIP_WechatInstance()
        {
            return GetSqlServerInstance(_conn_NIP_Wechat);
        }

        //创建获取老BPM NIP_Wechat_History SqlServer数据库
        public SqlSugarClient GetNIP_Wechat_HistoryInstance()
        {
            return GetSqlServerInstance(_conn_NIP_Wechat_History);
        }


        //创建获取SQLSugarClient 
        public SqlSugarClient GetInstance(string connectionString, string slaveConnectionString = "")
        {
            // 如果没有从库，则不使用从库
            if (string.IsNullOrWhiteSpace(slaveConnectionString))
            {
                //创建数据库对象
                var _dbClient = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = connectionString,//连接符字串
                    DbType = DbType.MySql,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute,//从特性读取主键自增信息
                    ConfigureExternalServices = new ConfigureExternalServices()
                    {
                        SqlFuncServices = _sqlFuncExtension.GetExpandSqlFuncs()
                    }
                });
                return _dbClient;
            }
            else
            {
                //创建数据库对象
                var _dbClient = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = connectionString,//连接符字串
                    DbType = DbType.MySql,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute,//从特性读取主键自增信息
                    ConfigureExternalServices = new ConfigureExternalServices()
                    {
                        SqlFuncServices = _sqlFuncExtension.GetExpandSqlFuncs()
                    },
                    //从库
                    SlaveConnectionConfigs = new List<SlaveConnectionConfig>() {
                     new SlaveConnectionConfig() { HitRate=10, ConnectionString=slaveConnectionString }
                }
                });
                return _dbClient;
            }



            //添加Sql打印事件，开发中可以删掉这个代码
            //_dbClient.Aop.OnLogExecuting = (sql, pars) =>
            //{
            //    _logger.LogInformation(sql);
            //};

            ////拦截SQL
            //_dbClient.Aop.OnExecutingChangeSql = (sql, pars) =>
            //{
            //    if (isReadOnly)
            //    {
            //        if (Regex.IsMatch(sql.TrimStart(), filterPattern, RegexOptions.IgnoreCase))
            //        {
            //            throw new InvalidOperationException("只读模式下不允许执行增删改操作。");
            //        }
            //    }

            //    return new KeyValuePair<string, SugarParameter[]>(sql, pars);
            //};

        }

        //创建获取SQLSugarClient SqlServer
        public SqlSugarClient GetSqlServerInstance(string connectionString)
        {
            //创建数据库对象
            var _dbClient = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = connectionString,//连接符字串
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute//从特性读取主键自增信息
            });
            ////添加Sql打印事件，开发中可以删掉这个代码
            //_dbClient.Aop.OnLogExecuting = (sql, pars) =>
            //{
            //    _logger.LogInformation(sql);
            //};
            return _dbClient;
        }
        //创建获取SUSAPI实例 
        public SqlSugarClient GetSUSInstance()
        {
            return GetInstance(_connSUS);
        }

        //创建获取SQLSugarClient PostgreSQL
        public SqlSugarClient GetPostgreSQLInstance(string connectionString)
        {
            //创建数据库对象
            var _dbClient = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = connectionString,//连接符字串
                DbType = DbType.PostgreSQL,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,//从特性读取主键自增信息
            });
            ////添加Sql打印事件，开发中可以删掉这个代码
            //_dbClient.Aop.OnLogExecuting = (sql, pars) =>
            //{
            //    _logger.LogInformation(sql);
            //};
            return _dbClient;
        }

        //创建获取ids NPPlatformManage实例 
        public SqlSugarClient GetNPPlatformManageInstance()
        {
            return GetPostgreSQLInstance(_connNPPlatformManage);
        }
    }
}
